package com.stylefeng.guns.rest.modular.wz.api.v3;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.AliyunSmsUtil;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.EnPfFile;
import com.stylefeng.guns.rest.enums.EnWzCoupon;
import com.stylefeng.guns.rest.enums.EnWzMapMerge;
import com.stylefeng.guns.rest.enums.EnWzMapRebate;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.WzShareApi;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzMapRebateServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: wz_dev_app_shop
 * @description: 返利接口
 * @author: Chenchao
 * @create: 2019-03-03 14:33
 **/
@RestController
@RequestMapping("/wz/api/v3/mapRebate/")
public class WzMapRebateApi extends ApiBaseController {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private WzMapRebateMapper mapRebateMapper;
    @Autowired
    private WzUserRebateMapper userRebateMapper;
    @Autowired
    private WzRebateShareMapper rebateShareMapper;
    @Autowired
    private WzMapRebateServiceImpl mapRebateService;
    @Autowired
    private PfOpenCityMapper openCityMapper;
    @Autowired
    private WzUserCouponMapper userCouponMapper;
    @Autowired
    private WzCouponMarketMapper couponMarketMapper;
    @Autowired
    private WzAdvMapMapper advMapMapper;


    /**
     * 去参与返利活动
     */
    @PostMapping("createUserRebate")
    public Res createUserRebate(@RequestBody ParamMap paramMap) throws Exception{
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");//返利活动id
        Res res = mapRebateService.createUserRebate(paramMap);
        return null;
    }

    /**
     * 返利详情
     */
    @PostMapping("detail")
    public Res detail(@RequestBody ParamMap paramMap) {
        Long mapRebateId=paramMap.getLongMisValid("mapRebateId");
        Long userCode=jwtTokenUtil.getUserCodeFromToken();
        //基本信息
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);

        WzAdvMap advMap = cacheService.advMap(mapRebate.getAdvMapId());//店铺信息
        WzCoupon coupon = cacheService.coupon(mapRebate.getCouponId());//券信息

        paramMap.put("pic",mapRebate.getPic());//图片
        paramMap.put("advMapId",advMap.getAdvMapId());//店铺id
        paramMap.put("rebatePrice",mapRebate.getRebatePrice());//返利价
        paramMap.put("merchantName",mapRebate.getMerchantName());//商户名称
        paramMap.put("merchantUserCode",mapRebate.getMerchantUserCode());//商户编号
        paramMap.put("merchantTel",advMap.getMerchantTel());//商户编号
        paramMap.put("benefit",mapRebate.getBenefit());//优惠信息
        paramMap.put("sales",mapRebate.getSales());//销量
        paramMap.put("couponBeginTime",coupon.getBeginTime());//券的开始时间
        paramMap.put("couponEndTime",coupon.getEndTime());//券的结束时间
        paramMap.put("rule",coupon.getRule());//券的使用规则
        paramMap.put("ruleType",coupon.getRuleType());//券的类型：1-文字；2-图片；
        paramMap.put("advMapShareLink",advMap.getShareLink());//店铺详情
        paramMap.put("price",coupon.getPrice());//券原价
        paramMap.put("logo",advMap.getLogo());//店铺logo
        paramMap.put("title",advMap.getName()+"在外赚有很多优惠活动，快去看看吧！");//分享标题
        paramMap.put("shareDescribe",advMap.getSubtitle());//分享描述
        paramMap.put("shareLink",mapRebate.getShareLink());//分享链接
        paramMap.put("couponId",coupon.getCouponId());//券id
        paramMap.put("needShareNumber",mapRebate.getNeedShareNumber());//最多分享人数
        paramMap.put("title","帮我点击下，我正在参加" + advMap.getName()+"的返利活动！");//分享标题
        paramMap.put("shareDescribe",advMap.getSubtitle());//分享描述
        paramMap.put("limitNumber",mapRebate.getLimitNumber());//每单限购数
        if(mapRebate.getCouponMarketId() != null){
            WzCouponMarket couponMarket = couponMarketMapper.selectById(mapRebate.getCouponMarketId());
            int limit = couponMarket.getTotalNumber() - mapRebate.getSales();
            if(limit < 0){
                paramMap.put("limitNumber",0);//每单限购数
            }else{
                if(mapRebate.getLimitNumber() > limit){
                    paramMap.put("limitNumber",limit);//每单限购数
                }
            }
        }
        paramMap.put("useType",coupon.getUseType());//使用方式
        //用户发起返利活动
        paramMap.put("myUserRebate",new HashMap<>());
        paramMap.put("used",0);//没有券可以使用
        String userRebateSql = "quantity,user_rebate_id AS userRebateId,end_time AS endTime,need_share_number As needShareNumber,share_number As shareNumber,rebate_price As rebatePrice,price";
        List<Map<String, Object>> userRebateList = userRebateMapper.selectMaps(new EntityWrapper<WzUserRebate>().setSqlSelect(userRebateSql).eq("map_rebate_id",mapRebate.getMapRebateId()).eq("user_code",userCode).eq("status",EnWzMapRebate.USERREBATE_STATUS_GOING.getIndex()));
        if(userRebateList.size() > 0){
            if(Consts.dev.equals("true")) {
                paramMap.put("shareLink", Consts.Adv_Share_Api_Domain_Test + "/wz/wzShare/mapRebate?mapRebateId=" + mapRebate.getMapRebateId() + "&userCode=" + userCode + "&userRebateId=" + userRebateList.get(0).get("userRebateId") + "&adCode=" + mapRebate.getAdCode());//分享链接
            }else {
                paramMap.put("shareLink", Consts.Adv_Share_Api_Domain + "/wz/wzShare/mapRebate?mapRebateId=" + mapRebate.getMapRebateId() + "&userCode=" + userCode + "&userRebateId=" + userRebateList.get(0).get("userRebateId") + "&adCode=" + mapRebate.getAdCode());//分享链接
            }

            String rebateShareSql = "avatar_url As avatarUrl,nick_name As nickName,create_time AS createTime";
            List<Map<String, Object>> rebateShares = rebateShareMapper.selectMaps(new EntityWrapper<WzRebateShare>().setSqlSelect(rebateShareSql).eq("user_rebate_id",Long.parseLong(userRebateList.get(0).get("userRebateId").toString())));
            userRebateList.get(0).put("rebateShares",rebateShares);
            paramMap.put("myUserRebate",userRebateList.get(0));
            int c = userCouponMapper.selectCount(new EntityWrapper<WzUserCoupon>().eq("user_rebate_id",userRebateList.get(0).get("userRebateId").toString()).eq("status", EnWzCoupon.UserCoupon_Status_Normal.getIndex()));
            if(c > 0){
                paramMap.put("used",1);
            }
        }
        //全部返利列表
        paramMap.put("allUserRebateList",new ArrayList<>());
        paramMap.put("allUserNumber",0);
        String userRebatesSql = "quantity,nick_name As nickName,avatar_url As avatarUrl,user_rebate_id AS userRebateId,end_time AS endTime,need_share_number As needShareNumber,share_number As shareNumber,rebate_price As rebatePrice,price";
        List<Map<String, Object>>  allUserMergeList = userRebateMapper.selectMaps(new EntityWrapper<WzUserRebate>().setSqlSelect(userRebatesSql).eq("map_rebate_id",mapRebate.getMapRebateId()).eq("status",EnWzMapRebate.USERREBATE_STATUS_GOING.getIndex()));
        if(allUserMergeList.size() > 0){
            paramMap.put("allUserRebateList",allUserMergeList);
            paramMap.put("allUserNumber",allUserMergeList.size());
        }
        return Res.success(paramMap);
    }

    /**
     * 返利列表
     */
    @PostMapping("list")
    public Res list(@RequestBody ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long userCode=jwtTokenUtil.getUserCodeFromToken();
        String switchAdCode = paramMap.getStrMisValid("switchAdCode");
        Integer advMapCategoryFirst = paramMap.getIntValid("advMapCategoryFirst");//0:全部
        Long advMapId = paramMap.getLongValid("advMapId");
        String keyWords = paramMap.getStrValid("keyWords");//搜索关键字


        EntityWrapper ew = new EntityWrapper<WzMapRebate>();
        ew.like("ad_code",switchAdCode).eq("status", EnWzMapRebate.STATUS_RELEASE.getIndex());
        if (advMapCategoryFirst != 0) {
            ew.eq("adv_map_category_first",advMapCategoryFirst);
        }

        if(StringUtils.isNotBlank(keyWords)) {
            String filterSql = "(merchant_name like '%" + keyWords + "%' or benefit like '%" + keyWords + "%')";
            ew.addFilter(filterSql);
        }

        if(advMapCategoryFirst == 0 && StringUtils.isBlank(keyWords)){
            ew.eq("is_recommend",1);
        }

        if(advMapId != null){//单个店铺活动
            ew.eq("adv_map_id",advMapId);
        }else{
            ew.eq("type",EnWzMapRebate.Type_My_Coupon.getIndex());
        }
        //返利活动列表
        String sql = "map_rebate_id AS mapRebateId,merchant_name AS merchantName,benefit,rebate_price AS rebatePrice,sales,pic";
        List<Map<String, Object>> rebateList = mapRebateMapper.selectMapsPage(new Page<>(pageNum, pageSize), ew.setSqlSelect(sql).orderBy("sort",true).orderBy("create_time",false));
        paramMap.put("rebateList",rebateList);
        //用户发起返利列表
        String userRebateSql = "quantity,map_rebate_id As mapRebateId,user_rebate_id AS userRebateId,end_time AS endTime,benefit,pic,share_number As shareNumber,need_share_number As needShareNumber,rebate_price As rebatePrice,price";
        List<Map<String, Object>> userRebateList = userRebateMapper.selectMaps(new EntityWrapper<WzUserRebate>().setSqlSelect(userRebateSql).eq("user_code",userCode).eq("status",EnWzMapRebate.USERREBATE_STATUS_GOING.getIndex()));
        paramMap.put("userRebateList",userRebateList);
        return Res.success(paramMap);
    }

    /**
     * 修改返利
     */
    @PostMapping("edit")
    public Res edit(@RequestBody ParamMap paramMap) throws Exception{
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);
        int needShareNumber=paramMap.getIntMisValid("needShareNumber");//需分享人数
        int rebatePrice = paramMap.getIntMisValid("rebatePrice");//返利价格
        int limitNumber=paramMap.getIntMisValid("limitNumber");//每单限购数

        WzCoupon coupon = cacheService.coupon(mapRebate.getCouponId());
        int amount = coupon.getPrice() - rebatePrice;
        int limit = amount/(Integer.parseInt(Consts.rebateLimit));
        if(coupon.getPrice() <= Integer.parseInt(Consts.rebateLimit)){
            limit = 1;
        }
        if(needShareNumber <=0){
            return Res.fail("分享人数不能为0！");
        }
        if(limitNumber < 1){
            return Res.fail("0！");
        }
        if(needShareNumber > limit){
            return Res.fail("最多只能分享"+limit+"人");
        }
        mapRebate.setNeedShareNumber(needShareNumber);
        mapRebate.setRebatePrice(rebatePrice);
        mapRebate.setStatus(EnWzMapRebate.STATUS_CHECKING.getIndex());
        mapRebate.setPrice(coupon.getPrice());
        mapRebate.setLimitNumber(limitNumber);
        mapRebate.setMerchantLogo(coupon.getLogo());
        mapRebate.setMerchantName(coupon.getMerchantName());
        //生成分享文章
        WzAdvMap advMap = advMapMapper.selectById(Long.parseLong(coupon.getAdvMapId()));
        String id = mapRebateService.shareLinkId(advMap,mapRebate,coupon,needShareNumber,rebatePrice);
        mapRebate.setShareLink(Consts.DOMAIN_SHARE+id+".html");
        boolean b = mapRebate.updateById();
        if (b) {
            if (Consts.dev.equals("false")) {
                for (String c : Consts.AuditorTel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c, "有返利活动修改需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        } else {
            return Res.fail();
        }
    }

    /**
     * 新增返利
     */
    @PostMapping("add")
    public Res add(@RequestBody ParamMap paramMap) throws Exception{
        Long couponId = paramMap.getLongMisValid("couponId");
        int rebatePrice = paramMap.getIntMisValid("rebatePrice");//返利价格
        int needShareNumber=paramMap.getIntMisValid("needShareNumber");//需分享人数
        int limitNumber=paramMap.getIntMisValid("limitNumber");//每单限购数
        WzCoupon coupon = cacheService.coupon(couponId);
        int amount = coupon.getPrice() - rebatePrice;
        int limit = amount/(Integer.parseInt(Consts.rebateLimit));
        if(coupon.getPrice() <= Integer.parseInt(Consts.rebateLimit)){
            limit = 1;
        }
        if(needShareNumber <=0){
            return Res.fail("分享人数不能为0！");
        }
        if(limitNumber < 1){
            return Res.fail("每单限购人数不能小于1！");
        }
        if(needShareNumber > limit){
            return Res.fail("最多只能分享"+limit+"人");
        }
        WzAdvMap advMap = cacheService.advMap(Long.parseLong(coupon.getAdvMapId()));
        WzMapRebate mapRebate = new WzMapRebate();
        mapRebate.setAdvMapId(advMap.getAdvMapId());
        mapRebate.setCouponId(couponId);
        mapRebate.setNeedShareNumber(needShareNumber);
        mapRebate.setRebatePrice(rebatePrice);
        mapRebate.setAdvMapCategoryFirst(advMap.getAdvMapCategoryFirst());
        mapRebate.setBeginTime(coupon.getBeginTime());
        mapRebate.setEndTime(coupon.getEndTime());
        mapRebate.setStatus(EnWzMapRebate.STATUS_CHECKING.getIndex());
        mapRebate.setCreateTime(new Date());
        mapRebate.setPrice(coupon.getPrice());
        mapRebate.setLimitNumber(limitNumber);
        mapRebate.setPic(coupon.getPic());
        mapRebate.setMerchantName(coupon.getMerchantName());
        mapRebate.setMerchantLogo(coupon.getLogo());
        mapRebate.setMerchantUserCode(advMap.getUserCode());
        mapRebate.setBenefit(coupon.getBenefit());
        mapRebate.setAdCode(advMap.getAdCode());
        mapRebate.setType(EnWzMapRebate.Type_My_Coupon.getIndex());

        //生成分享文章
        String id = mapRebateService.shareLinkId(advMap,mapRebate,coupon,needShareNumber,rebatePrice);

        mapRebate.setShareLink(Consts.DOMAIN_SHARE+id+".html");
        boolean b = mapRebate.insert();
        if (b) {
            if (Consts.dev.equals("false")) {
                for (String c : Consts.AuditorTel) {
                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c, "有新的返利活动需要审核", Consts.ADMIN_TEMPLATE_CODE);
                }
            }
            return Res.success();
        } else {
            return Res.fail();
        }
    }

    /**
     * 下架返利活动
     */
    @PostMapping("pullOff")
    public Res pullOff(@RequestBody ParamMap paramMap) {
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);
        if(mapRebate.getStatus()!=EnWzMapRebate.STATUS_RELEASE.getIndex()){
            return Res.fail("当前状态不可下架！");
        }
        mapRebate.setStatus(EnWzMapRebate.STATUS_Down.getIndex());
        int r = mapRebateMapper.updateById(mapRebate);
        if(r > 0){
            return Res.success();
        }else{
            return Res.fail();
        }
    }

    /**
     * 返利记录
     */
    @PostMapping("mapRebateReward")
    public Res mapRebateReward(@RequestBody ParamMap paramMap){
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");

        String sql = "nick_name AS nickName,avatar_url AS avatarUrl,quantity,status,share_number As shareNumber,price,rebate_price As rebatePrice,need_share_number As needShareNumber,rebate_amount As rebateAmount";
        List<Map<String, Object>> userRebateList = userRebateMapper.selectMapsPage(new Page<>(pageNum, pageSize),new EntityWrapper<WzUserRebate>().setSqlSelect(sql).eq("map_rebate_id",mapRebateId).ne("status",EnWzMapRebate.USERREBATE_STATUS_Wait_Pay.getIndex()));
        return Res.success(paramMap.data(userRebateList));
    }

    /**
     * 创建返利活动
     */
    @PostMapping("createRebate")
    public Res createRebate(@RequestBody ParamMap paramMap) throws Exception{
        Long userCode = jwtTokenUtil.getUserCodeFromToken();//下单用户编号
        Long mapRebateId = paramMap.getLongMisValid("mapRebateId");//返利活动id
        int quantity = paramMap.getIntMisValid("quantity");//购买数量
        int amount = paramMap.getIntMisValid("amount");//前台计算价格
        int isRewardBalanceDeduction = paramMap.getIntMisValid("isRewardBalanceDeduction");//是否用积分余额抵扣：0-否;1-是
        int payMethod = paramMap.getIntMisValid("payMethod");//支付类型：1-支付宝;2-微信;
        WzUser user = cacheService.user(userCode);//用户信息

        int r = userRebateMapper.selectCount(new EntityWrapper<WzUserRebate>().eq("user_code",userCode).eq("map_rebate_id",mapRebateId).eq("status",EnWzMapRebate.USERREBATE_STATUS_GOING.getIndex()));
        if(r > 0){
            return Res.fail("正在参与返利活动!");
        }
        WzMapRebate mapRebate = mapRebateMapper.selectById(mapRebateId);//返利活动

        int limitNumber = mapRebate.getLimitNumber();
        if(mapRebate.getCouponMarketId() != null){
            WzCouponMarket couponMarket = couponMarketMapper.selectById(mapRebate.getCouponMarketId());
            int limit = couponMarket.getTotalNumber() - mapRebate.getSales();
            if(limit < 0){
                limitNumber = 0;
            }else{
                if(limitNumber > limit){
                    limitNumber = limit;
                }
            }
        }
        if(quantity > limitNumber){
            return Res.fail("每单限购" + limitNumber + "件!");
        }

        //后台金额计算
        int realAmount = quantity * mapRebate.getPrice();

        //现金支付
        if(isRewardBalanceDeduction == 0){
            if(amount != realAmount){
                return Res.fail("金额错误!");
            }
            Res res = mapRebateService.createRebate(paramMap,user,mapRebate,payMethod,quantity,realAmount);
            return res;
        }
        return Res.fail();
    }

    /**
     * 我的返利活动
     */
    @PostMapping("myUserRebates")
    public Res myUserRebates(@RequestBody ParamMap paramMap){
        Long userCode=jwtTokenUtil.getUserCodeFromToken();
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        int status = paramMap.getIntMisValid("status");
        String sql = "user_rebate_id As userRebateId,quantity,need_share_number As needShareNumber,map_rebate_id As mapRebateId,pic,benefit,price,rebate_price As rebatePrice,rebate_amount As rebateAmount,end_time As endTime,share_number As shareNumber";
        List<Map<String, Object>> userRebateList = userRebateMapper.selectMapsPage(new Page<>(pageNum, pageSize),new EntityWrapper<WzUserRebate>().setSqlSelect(sql).eq("user_code",userCode).eq("status",status));
        for(Map<String, Object> map : userRebateList){
            String rebateShareSql = "avatar_url As avatarUrl,nick_name As nickName,create_time AS createTime";
            List<Map<String, Object>> rebateShares = rebateShareMapper.selectMaps(new EntityWrapper<WzRebateShare>().setSqlSelect(rebateShareSql).eq("user_rebate_id",Long.parseLong(map.get("userRebateId").toString())));
            map.put("rebateShares",rebateShares);
        }
        return Res.success(paramMap.data(userRebateList));
    }
}
